var http = require('http');
var fs = require('fs');
const host = '127.0.0.1';
const port = 5000;

const QHInit = require('./QHInit.js');
const { QHApi, QHNotify } = new QHInit();

//创建服务器，参数就是一个回调函数，表示如果有请求进来，要做什么
var app = http.createServer(function (request, response) {
    //req表示请求， request；res表示响应，response
    var { url, method } = request;
    console.log(url, method, 'QHRead demo get request!');
    response.writeHead(200, { 'Content-type': 'application/json;charset=UTF-8' });
    if (['/', '/index', '/index.html'].includes(url)) {
        fs.readFile('./demo/index.html', function (err, data) {
            //设置HTTP头部，状态码是200，文件类型是html，字符集是utf8
            response.writeHead(200, { 'Content-type': 'text/html;charset=UTF-8' });
            response.end(data);
        });
    } else if ('/getTaskList' == url) {
        QHApi.getTaskList({ user_id: '387' }, function (err, res) {
            response.end(JSON.stringify(err || res));
        });
    } else if ('/getReadTask' == url) {
        QHApi.getReadTask({ user_id: '387' }, function (err, res) {
            response.end(JSON.stringify(err || res));
        });
    } else if ('/notify' == url) {
        var body = [];
        request.on('data', function (chunk) {
            body.push(chunk);
        });
        request.on('end', function (chunk) {
            QHNotify.notifyProcess(JSON.parse(body.toString()), function (res) {
                console.log('request:', body.toString());
                console.log('response:', JSON.stringify(res));
                response.end(JSON.stringify(res));
            });
        });
    } else {
        response.end('Hello World!');
    }
}).on('error', function (e) {
    console.log('Got error: ' + e.message);
});

//运行服务器，监听5000端口
app.listen(port, host);
console.log('QHRead demo is running!');
